<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>微信公众号推送授权</title>
  <style>
    .content{
      padding: 10px;
    }
    .content .tip{
      text-align: center;
    }
  </style>
</head>
<body>
  <div class="content">
    <div class="tip">正在获取授权...</div>
  </div>
</body>
<script src="https://res.wx.qq.com/open/js/jweixin-1.4.0.js"></script>
<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.4/jquery.min.js"></script>
<script>
  // 变量
  

  // 方法：获取参数
  const getParams = (name) => {
    var search = window.location.search.substring(1)
    if (!search) {
        search = window.location.hash.split('?')[1]
    }
    if (search) {
        var obj = JSON.parse('{"' + decodeURIComponent(search).replace(/"/g, '\\"').replace(/&/g, '","').replace(/=/g, '":"') + '"}')
        return name ? obj[name] : obj
    }
  }

  // // 方法：微信授权
  // const getAppId = (token) => {
  //   let appid = 'wx34bddd7989014148';
  //   let redirect_uri = window.location.href // 授权登录成功回调的地址，一般为当前页// 授权操作是直接访问腾讯开放平台的一个授权地址，授权成功后会回调
  //   console.log(redirect_uri);
  //   window.location = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=' + appid + '&redirect_uri=' + redirect_uri + '&response_type=code&scope=snsapi_userinfo&state=' + token + '#wechat_redirect' //引导用户授权
  // }

  // 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=' + appid + '&redirect_uri=' + redirect_uri + '&response_type=code&scope=snsapi_userinfo&state=' + token + '#wechat_redirect' //引导用户授权

  const sendCode = (code, token) => {
    try{
        $.get({
        url: "https://xyxl.ranxuxing.com/api/user/official_bind",
        headers: {
          "token": token
        },
        data: {
          code: code
        },
        success(res){
          console.log(res);
          if(res.code == 1){
            $(".tip").text("获取授权成功，您可以退出此页面了！");
            setTimeout(() => {
              wx.miniProgram.redirectTo({ url: "/pages/personal/personal" })
            },1000)
          }else{
            $(".tip").text("获取授权失败，" + res.msg);
          }
        },
        error(err){
          let msg = err.responseJSON.msg;
          console.log(msg);
          $(".tip").text("获取授权失败，" + msg);
        }
      })
    }catch{
      $(".tip").text("获取授权失败");
    }
  }


  window.onload = function (){
    console.log("页面载入")
    let token = getParams("token");
    let code = getParams("code");
    let state = getParams("state");
    sendCode(code,state);
    // if(code){
    //   console.log("成功！",code,state);
    //   sendCode(code,state);
    // }else{
    //   getAppId(token);
    // }
  }
</script>
</html>